from sys import argv
from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *

# 三角形顶点
points = [[-0.9,-0.9], [0.9,-0.9], [0,0.9]]
# 图形窗口初始尺寸
width, height = 640, 640
# 控制旋转角度
angle = 0

def triangle(points):
    # 绘制三角形
    glBegin(GL_TRIANGLES)
    for p in points:
        glVertex2fv(p)
    glEnd()

def draw():
    glClear(GL_COLOR_BUFFER_BIT)
    glLoadIdentity()
    glColor3f(0,0,0)
    glLineWidth(3)
    glViewport(0,0,width,height)
    glBegin(GL_LINES)
    glVertex2fv((-2,0))
    glVertex2fv((2,0))
    glVertex2fv((0,-2))
    glVertex2fv((0,2))
    glEnd()
    glViewport(0,0,width//2,height//2)
    glColor3f(0,0.5,1)
    glRotate(angle,0,0,1)
    triangle(points)
    
    glViewport(width//2,height//2,width//2,height//2)
    glColor3f(0,1,0.5)
    glLoadIdentity()
    glRotate(90,0,0,1)
    glRotate(angle*3,0,0,1)
    triangle(points)


    glViewport(0,height//2,width//2,height//2)
    glColor3f(0.5,1,0)
    glLoadIdentity()
    glRotate(180,0,0,1)
    glRotate(-angle,0,0,1)
    triangle(points)
    
    glViewport(width//2,0,width//2,height//2)
    glColor3f(1,0.5,1)
    glLoadIdentity()
    glRotate(-90,0,0,1)
    glRotate(-angle*3,0,0,1)
    triangle(points)

    glFlush()
    
def reshape(w, h):
    # 修改全局变量，使得4个视窗自动适应新窗口大小
    global width, height
    width, height = w, h

def change_angle(value):
    global angle
    angle = angle +1
    glutPostRedisplay()
    glutTimerFunc(200,change_angle,0)
    
def main(width=640, height=640, title='多视口显示旋转三角形'):
    glutInit(len(argv), argv)
    glutInitDisplayMode(GLUT_RGBA)
    glutInitWindowSize(width, height)
    glutInitWindowPosition(400, 100)
    glutCreateWindow(title.encode('gbk'))
    glutDisplayFunc(draw)
    glutReshapeFunc(reshape)
    glutTimerFunc(100, change_angle, 0)
    # 初始化窗口背景为白色
    glClearColor(1.0, 1.0, 1.0, 1.0)
    # 切换到投影变换矩阵，使用正交投影
    glMatrixMode(GL_PROJECTION)
    gluOrtho2D(-2,2,-2,2)
    glMatrixMode(GL_MODELVIEW)
    
    glutMainLoop()

if __name__ == '__main__':
    main(width, height)
